package com.esyoga.yoyoga.handler;

import lombok.Data;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Data
@Controller
@RequestMapping("/momentsimage")
public class MomentsImageUpdateHandler {
    @RequestMapping("/momentsImageUpdate")
    @ResponseBody
    public Object momentsImageUpdate(@RequestParam(value="file",required=false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String result="";
        //System.out.println(studentPOJO);
        //System.out.println(file);
        //执行到此处，前端提交的数据全拿到了
        //1.将文件保存到Tomcat服务器本地
        //1.1.获取保存文件的文件夹的路径
        String path =  request.getServletContext().getRealPath("/imagge");
       // System.out.println(path);

        File dir = new File(path);
        //获得webapp文件夹的file对象
        File webapp = dir.getParentFile();
        //获取/创建image文件夹
        File image = new File(webapp, "imagge");
        if (!image.exists()) {
            image.mkdirs();//创建文件夹
        }
        String fileName = file.getOriginalFilename();

        //生成新文件名
        String newName = UUID.randomUUID().toString();

        //得到文件后缀名
        String type = fileName.substring(fileName.lastIndexOf("."));
        //
        newName+=type;
       // System.out.println("=================================================================");
        //System.out.println(newName);
        //拼接新文件的路径
        File uploadFile  = new File(image,newName);

        //1.2.将文件保存到服务器本地
        file.transferTo(uploadFile);

        Map<String,Object> map2=new HashMap<>();
        Map<String,Object> map=new HashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("src",newName);


        return map;
    }
}
